Imports System.IO

Friend Class libCRC32

    ' This code is taken from the VB.NET CRC32 algorithm
    ' provided by Paul (wpsjr1@succeed.net) - Excellent work!

    Private crc32Table() As UInt32

    Sub New()
        Dim dwPolynomial As UInt32
        dwPolynomial = &HEDB88320L
        Dim i As Integer, j As Integer

        ReDim crc32Table(256)
        Dim dwCrc As Long

        For i = 0 To 255
            dwCrc = i
            For j = 8 To 1 Step -1
                If (dwCrc And 1) Then
                    dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                    dwCrc = dwCrc Xor dwPolynomial
                Else
                    dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                End If
            Next j
            crc32Table(i) = dwCrc
        Next i

    End Sub

    Friend Function GetByteArrayCrc32(ByRef buffer() As Byte, Optional ByVal Start As ULong = 0, Optional ByVal Length As ULong = 0) As UInt32

        Dim crc32Result As UInt32
        crc32Result = &HFFFFFFFFL

        If Start > buffer.Length Then
            Start = 0
        End If
        If Length = 0 Then
            Length = buffer.Length - Start
        End If
        If Start + Length > buffer.Length Then
            Length = buffer.Length - Start
        End If

        Dim iLookup As Long

        For i As Integer = Start To Start + Length - 1
            iLookup = (crc32Result And &HFF) Xor buffer(i)
            crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And 16777215 ' nasty shr 8 with vb :/
            crc32Result = crc32Result Xor crc32Table(iLookup)
        Next

        Return Not (crc32Result)

    End Function

    Friend Function GetFileCrc32(ByRef stream As MemoryStream) As UInt32
        Return Me.GetByteArrayCrc32(stream.ToArray)
    End Function
End Class
